//
//  LSZSetUpVC.m
//  PartyClassCloud
//
//  Created by 梁素珍 on 2018/8/16.
//  Copyright © 2018年 九酷. All rights reserved.
//

#import "LSZSetUpVC.h"

#import <AssetsLibrary/AssetsLibrary.h>//判断拍照和相册是否授权
@interface LSZSetUpVC ()<UITableViewDelegate,UITableViewDataSource,LDImagePickerDelegate,UINavigationControllerDelegate>
@property(nonatomic,strong) UITableView * tableViewSetUp;

@end

@implementation LSZSetUpVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"设置";
    self.tableViewSetUp = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight) style:UITableViewStyleGrouped];
    self.tableViewSetUp.delegate = self;
    self.tableViewSetUp.dataSource = self;
    self.tableViewSetUp.estimatedRowHeight=0;
    self.tableViewSetUp.estimatedSectionFooterHeight =0;
    self.tableViewSetUp.estimatedSectionHeaderHeight =0;
    [self.tableViewSetUp setSeparatorInset:UIEdgeInsetsMake(0, 20, 0, 20)];
    [self.view addSubview:self.tableViewSetUp];
    
    [self.tableViewSetUp registerClass:[LSZHeadPortraitTableViewCell class] forCellReuseIdentifier:@"LSZHeadPortraitTableViewCell"];
    [self.tableViewSetUp registerClass:[LSZOneLabelTableViewCell class] forCellReuseIdentifier:@"LSZOneLabelTableViewCell"];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(section == 0 ){
        return 1;
    }else{
        return 2;
    }
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return 80;
    }else{
        return 45;
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 10;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.001;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        LSZHeadPortraitTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"LSZHeadPortraitTableViewCell" forIndexPath:indexPath];
        cell.labelHeader.text = @"头像";
        if ([_MyCenter headUrl].length == 0) {
            cell.imageViewHeader.image = [UIImage imageNamed:@"头像默认"];
        }else{
            [cell.imageViewHeader sd_setImageWithURL:[NSURL URLWithString:[_MyCenter headUrl]] placeholderImage:[UIImage imageNamed:@"默认"]];
        }
        cell.selectionStyle = UITableViewCellSeparatorStyleNone;
        return cell;
    }else{
        LSZOneLabelTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"LSZOneLabelTableViewCell" forIndexPath:indexPath];
        if (indexPath.row == 0) {
            cell.labelTiele.text = @"修改密码";
            cell.labelRight.hidden = YES;
        }else{
            cell.labelTiele.text = @"性别";
            cell.labelRight.hidden = NO;
            cell.labelRight.text = [_MyCenter sex];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        [self ModifyThePicture];
    }else{
        if (indexPath.row == 0) {
            LSZChangePasswordVC * vc = [[LSZChangePasswordVC alloc]init];
            [self.navigationController pushViewController:vc animated:YES];
        }else{
            ACActionSheet *actionSheet = [[ACActionSheet alloc] initWithTitle:nil cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@[@"男",@"女"] actionSheetBlock:^(NSInteger buttonIndex) {
                if(buttonIndex ==0) {
                    [self setWithString:@"男"];
                }else if (buttonIndex == 1){
                    [self setWithString:@"女"];
                }
            }];
            [actionSheet show];
        }
    }
}
-(void)setWithString :(NSString *)stringSex
{
    [LSZRequestData initWithModifyTheGender:stringSex :^(BOOL isOk, NSString * string, NSString * str) {
        if(isOk == YES){
            [self initWithtring:@"性别修改成功!"];
            [_MyCenter setSex:NullStringjudgment(NSStr(stringSex))];
            [self.tableViewSetUp reloadData];
        }
    }];
}
#pragma mark - 修改头像
-(void)ModifyThePicture
{
    __weak typeof(self) weakSelf = self;
    ACActionSheet *actionSheet = [[ACActionSheet alloc] initWithTitle:nil cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@[@"相册",@"拍照"] actionSheetBlock:^(NSInteger buttonIndex) {
        if(buttonIndex ==0) {
            [weakSelf initWithPhoneFromThePhotoAlbum];
        }else if (buttonIndex == 1){
            [weakSelf initWithPhoneTakingpictures];
        }
    }];
    [actionSheet show];
}
#pragma mark - 拍照
-(void)initWithPhoneTakingpictures
{
    NSUInteger sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    // 判断是否支持相机
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        //来源:相机
        sourceType = UIImagePickerControllerSourceTypeCamera;
//        NSString * mediaType = AVMediaTypeVideo;
//        AVAuthorizationStatus  authorizationStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType];
//        if (authorizationStatus == AVAuthorizationStatusRestricted|| authorizationStatus == AVAuthorizationStatusDenied) {
//            [self initWithtring:@"摄像头访问受限,请打开摄像头允许拍摄!"];
//            return;
//        }
//        NSString * mediaType = AVMediaTypeVido;
    }
    else {
        [self initWithtring:@"此设备没有摄像功能!"];
        return;
    }
    // 跳转到相机或相册页面
    LDImagePicker *imagePicker = [LDImagePicker sharedInstance];
    imagePicker.delegate = self;
    //设置宽高比scale来设置剪切框大小，剪切框宽度固定为屏幕宽度
    [imagePicker showImagePickerWithType:0   InViewController:self Scale:1];
}
#pragma mark - 从相册里面查找
-(void)initWithPhoneFromThePhotoAlbum
{
    NSUInteger sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    // 判断是否支持相机
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        //来源:相册//来自图库
        sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        ALAuthorizationStatus author = [ALAssetsLibrary authorizationStatus];
        if (author == ALAuthorizationStatusRestricted || author == ALAuthorizationStatusDenied){
            //无权限
            [self initWithtring:@"照片访问受限,请允许app访问你的照片!"];
            return;
        }
    }
    else {
        //来自相册
        sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
        ALAuthorizationStatus author = [ALAssetsLibrary authorizationStatus];
        if (author == ALAuthorizationStatusRestricted || author == ALAuthorizationStatusDenied){
            //无权限
            [self initWithtring:@"照片访问受限,请允许app访问你的照片!"];
            return;
        }
    }
    // 跳转到相机或相册页面
    LDImagePicker *imagePicker = [LDImagePicker sharedInstance];
    imagePicker.delegate = self;
    //设置宽高比scale来设置剪切框大小，剪切框宽度固定为屏幕宽度
    [imagePicker showImagePickerWithType:1   InViewController:self Scale:1];
}
- (void)imagePicker:(LDImagePicker *)imagePicker didFinished:(UIImage *)editedImage{
    UIImage *imagestr = editedImage;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
    NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:@".png"]];   // 保存文件的名称
    BOOL result = [UIImagePNGRepresentation(imagestr)writeToFile: filePath    atomically:YES]; // 保存成功会返回YES
    LSZHeadPortraitTableViewCell * cell = (LSZHeadPortraitTableViewCell *)[self.tableViewSetUp cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0  inSection:0]];
    cell.imageViewHeader.image = editedImage;
    //需要在此处上传服务器
    __weak typeof(self) weakSelf = self;
    [LSZRequestData UploadFile:filePath imageView:editedImage :^(BOOL isOk, NSString * string, NSString * str) {
        if (isOk == YES) {
            NSString * strUrl = [NSString stringWithFormat:@"%@%@",URLTotal,str];
            [LSZRequestData initWithUploadTheAvatarUrlToTheServer:str :^(BOOL isok, NSString * str, NSString * string) {
                if (isok == YES) {
                    [weakSelf initWithtring:@"头像上传成功!"];
                    [_MyCenter setHeadUrl:strUrl];
                }else{
                    [weakSelf initWithtring:@"头像上传失败!"];
                }
            }];
        }else{
            [weakSelf initWithtring:@"头像上传失败!"];
        }
    }];
}
//用户点击图像选取器中的“cancel”按钮时被调用，这说明用户想要中止选取图像的操作
-(void)imagePickerDidCancel:(LDImagePicker *)imagePicker
{
}
@end
